from app import app, db, User, Product, EmailVerification
from datetime import datetime
from config import DEFAULT_AVATAR, STATIC_FOLDER
import json
import os
import shutil

# 1. 删除所有表并重新创建
with app.app_context():
    db.drop_all()
    db.create_all()
    print("数据库表已重置")

# 2. 确保静态资源目录存在
os.makedirs(os.path.dirname(os.path.join(STATIC_FOLDER, DEFAULT_AVATAR)), exist_ok=True)
os.makedirs(os.path.join(STATIC_FOLDER, 'images/products'), exist_ok=True)
print("已创建必要的目录")

# 3. 复制默认头像
default_avatar_path = os.path.join(STATIC_FOLDER, DEFAULT_AVATAR)
if not os.path.exists(default_avatar_path):
    shutil.copy('static/images/default_avatar.png', default_avatar_path)
    print("已复制默认头像")

# 4. 创建管理员用户
with app.app_context():
    admin = User(
        email='admin@example.com',
        username='管理员',
        password='123456',
        points=1000,
        avatar=DEFAULT_AVATAR,
        gender='男',
        age=18,
        city='未设置',
        bio='这个人很懒，什么也没留下...'
    )
    db.session.add(admin)
    
    # 5. 从 JSON 文件加载商品数据
    with open('products.json', 'r', encoding='utf-8') as f:
        products_data = json.load(f)
        for product_info in products_data['products']:
            product = Product(
                name=product_info['name'],
                points_required=product_info['points_required'],
                description=product_info['description'],
                image=product_info['image'],
                stock=product_info['stock'],
                category=product_info['category']
            )
            db.session.add(product)
    
    try:
        db.session.commit()
        print(f"\033[92m管理员邮箱:{User.email},密码:{User.password}\033[0m")
        print("数据初始化完成！")
    except Exception as e:
        db.session.rollback()
        print(f"数据初始化失败：{str(e)}") 